<script lang="ts" setup>
import type { PropType } from "vue";
import { deepClone } from "@/utils";
import BasePrizeFormItem from "./components/BasePrizeFormItem.vue";
import PricePrizeFormItem from "./components/PricePrizeFormItem.vue";
import StockPrizeFormItem from "./components/StockPrizeFormItem.vue";
import SpecSelectFormItem from "./components/SpecSelectFormItem.vue";

const props = defineProps({
  modelValue: {
    type: Object as PropType<any>,
  },
  poolType: {
    type: Number,
    default: 1,
  },
  goodsId: {
    type: Number,
  },
});

const emits = defineEmits(["update:modelValue"]),
  activityModel: string = inject("activityModel", "");

const formRef = ref();

const form: any = computed({
  get: () => {
    let update = false;
    if (props.modelValue.originalStock === undefined) {
      update = true;
      props.modelValue.originalStock = props.modelValue.stock || 0;
    }

    if (props.modelValue.originalStockTotal === undefined) {
      update = true;
      props.modelValue.originalStockTotal = props.modelValue.totalStock || 0;
    }
    if (update) emits("update:modelValue", props.modelValue);
    return props.modelValue;
  },
  set: (val) => {
    console.log(val, "set");

    emits("update:modelValue", val);
  },
});

// 加减库存
const changeSType: any = () => {
  formRef.value.validateField("num");
};

const check = () => {
  return new Promise((resolve, reject) => {
    formRef.value.validate(async (valid: boolean) => {
      if (valid) {
        let detail: any = deepClone(form.value);
        detail.stock =
          detail.stype == 1
            ? detail.originalStock + detail.num || 0
            : detail.originalStock - detail.num || 0;
        detail.totalStock =
          detail.stype == 1
            ? detail.originalStockTotal + detail.num || 0
            : detail.originalStockTotal - detail.num || 0;
        detail.payPrice = parseInt((Number(detail.payPrice) * 100).toFixed(2).slice(0, -3));
        resolve(detail);
      } else reject("");
    });
  });
};

defineExpose({ check });
</script>
<template>
  <el-form ref="formRef" :model="form" label-width="auto">
    <SpecSelectFormItem v-model="form" :disabled="form.id !== undefined" :goodsId="goodsId" />
    <BasePrizeFormItem v-model="form" :label="['规格名称', '规格图片']" />
    <el-form-item label="状态:" prop="onlineStatus" v-if="activityModel !== 'edit' || form.id === undefined">
      <el-switch v-model="form.onlineStatus" inline-prompt active-text="上架" inactive-text="下架" :active-value="1"
        :inactive-value="0" />
    </el-form-item>
    <product-original-price-readonly label-str="供货价" :value="form.costPrice" />
    <PricePrizeFormItem v-model="form" :pool-type="poolType" />
    <StockPrizeFormItem v-if="activityModel !== 'edit' || form.id === undefined" v-model="form"
      @check="changeSType(index)" />
  </el-form>
</template>
